package com.yun.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.blog.bean.Category;
import com.yun.blog.bean.Result;
import com.yun.blog.service.CategoryService;
import com.yun.blog.utils.FileUtils;
import com.yun.blog.utils.QianiuUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * title        : CategoryController
 * projectName  : dantouBlog-back
 * description  : 分类请求接口
 * author       : simple
 * date         : 2022/11/27下午10:08
 */

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    CategoryService categoryService;

    @GetMapping("/getCategoryById")
    public Result getCategoryById(Integer categoryId) {
        try {
            Category category = categoryService.getByCategoryId(categoryId);
            return Result.success("获取成功！").add("category", category);
        } catch (Exception e) {
            log.error("获取失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/saveCategory")
    public Result saveTag(@RequestBody Category category) {
        // 先判断是否存在
        if (categoryService.getByCategoryName(category.getCategoryName()) != null) {
            return Result.fail("分类已存在");
        }

        try {
            categoryService.save(category);
        } catch (Exception e) {
            log.error("保存失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("保存成功！");
    }

    @PostMapping("/updateCategory")
    public Result updateCategory(@RequestBody Category category) {
        // 先判断标签名称是否存在
        Category Category1 = categoryService.getByCategoryName(category.getCategoryName());
        if (Category1 != null && !Category1.getCategoryId().equals(Category1.getCategoryId())) {
            return Result.fail("分类名称已存在");
        }

        try {
            categoryService.updateById(category);
        } catch (Exception e) {
            log.error("修改分类失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("修改成功！");
    }

    @GetMapping("/deleteCategory")
    public Result deleteCategory(Integer categoryId) {
        try {
            categoryService.removeById(categoryId);
        } catch (Exception e) {
            log.error("删除失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("删除成功！");
    }

    @PostMapping("/deleteMany")
    public Result deleteMany(@RequestBody ArrayList<Integer> ids) {
        log.info("ids:{}", ids);
        try {
            categoryService.removeByIds(ids);
        } catch (Exception e) {
            log.error("删除失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("删除成功！");
    }

    @GetMapping("/getCategories")
    public Result getCategories(@RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "") String searchText) {
        log.info("pageSize:{}", pageSize);
        log.info("pageNum:{}", pageNum);
        log.info("searchText:{}", searchText);
        Result success = Result.success();
        // LambdaQueryWrapper<Category> queryWrapper = Wrappers.lambdaQuery();
        // // 如果有查询条件就查询名称一样的
        // if (StringUtils.hasText(searchText)) {
        //     queryWrapper.like(Category::getCategoryName, searchText);
        // }
        Page<Category> page = categoryService.customPage(new Page<>(pageNum, pageSize), searchText);

        success.add("page", page);
        return success;
    }

    /**
     * 获取全部分类
     *
     * @return java.util.List<com.yun.blog.bean.Category>
     **/
    @GetMapping("/getAllCategories")
    public List<Category> getAllCategories() {
        try {
            return categoryService.list();
        } catch (Exception e) {
            log.error("获取全部分类出错，错误信息为：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 获取全部分类
     *
     * @return java.util.List<com.yun.blog.bean.Category>
     **/
    @GetMapping("/getAllUseCategories")
    public List<Category> getAllUseCategories() {
        try {
            return categoryService.getByIsUse(true);
        } catch (Exception e) {
            log.error("获取全部分类出错，错误信息为：{}", e.getMessage());
            return null;
        }
    }

    @PostMapping("/uploadIcon")
    public Result uploadIcon(MultipartFile categoryIcon) {
        Result fail = Result.fail();
        if (categoryIcon == null || categoryIcon.isEmpty()) {
            fail.setMsg("图片不能为空！");
            return fail;
        }
        String filename = categoryIcon.getOriginalFilename();
        boolean allowPic = FileUtils.isAllowPic(filename);
        if (!allowPic) {
            fail.setMsg("图片类型不正确！");
            return fail;
        }

        try {
            // String iconPath = saveImg(categoryIcon, "categoryIcon");
            String iconPath = QianiuUploadUtils.upload(categoryIcon, "categoryIcon");
            Result success = Result.success("图片保存成功！");
            success.add("iconPath", iconPath);
            return success;
        } catch (Exception e) {
            log.error("图片保存失败！，错误信息为：{}", e.getMessage());
            fail.setMsg("图片保存失败！，错误信息为：" + e.getMessage());
            return fail;
        }
    }

}
